<template>
    <div class="app-manage">
        <div class="query-form">
            <el-form ref="form" :inline="true" :model="queryForm">
                <el-form-item label="应用名称" prop="appName">
                    <el-input v-model="queryForm.appName" placeholder="请输入应用名称" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button @click="handleReset('form')">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="base-table">
            <div class="action">
                <el-button type="primary" @click="handleCreate">新增</el-button>
                <el-button type="danger" @click="handlePatchDelete">批量删除</el-button>
            </div>
            <el-table :data="appList" @selection-change="handleSelectionChange" border cell-style="padding: 4px 0"
                max-height="600">
                <el-table-column type="selection" width="40" align="center" />
                <el-table-column v-for="item in columns" :key="item.prop" :prop="item.prop" :label="item.label"
                    :width="item.width" :formatter="item.formatter" align="center" />
                <el-table-column label="操作" width="220" align="center">
                    <template #default="scope">
                        <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination class="pagination" background layout="prev, pager, next" :total="pager.totalCount"
                :page-size="pager.pageSize" @current-change="handleCurrentChange" />
        </div>
        <el-dialog :title="action == 'add' ? '应用新增' : '应用修改'" v-model="showModal" :close-on-click-modal="false"
            :show-close="false" width="500px" center>
            <el-form ref="dialogForm" :model="appForm" label-width="100px" :rules="rules">
                <el-form-item label="应用名称" prop="appName">
                    <el-input v-model="appForm.appName" placeholder="请输入应用名称" />
                </el-form-item>
                <el-form-item label="应用类型" prop="appType">
                    <el-select v-model="appForm.appType" size="medium" style="width: 100%;" clearable>
                        <el-option value='0' label="安卓端"></el-option>
                        <el-option value='1' label="苹果端"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="应用版本" prop="version">
                    <el-input v-model="appForm.version" placeholder="请输入应用版本" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="appForm.remark" placeholder="请输入备注" />
                </el-form-item>
                <el-form-item label="应用地址" prop="version">
                    <el-input v-model="appUrl" placeholder="请上传应用地址" :disabled="true" />
                </el-form-item>
                <el-form-item>
                    <el-upload class="upload-app" action="void" :http-request="uploadFile" :name="file"
                        :multiple="false" ref="upload" :show-file-list="false" :auto-upload="true">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleClose">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog v-model="showProgress" :close-on-click-modal="false" :show-close="false" width="450px" center>
            <el-progress :text-inside="true" :stroke-width="24" :percentage="upLoadProgress"
                status="success"></el-progress>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleProgressClose">关闭</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { getCurrentInstance, onMounted, reactive, ref, toRaw } from 'vue'
import axios from 'axios'
import utils from "../utils/utils";
export default {
    name: 'application',
    setup() {
        //获取Composition API上下文对象
        const { ctx, proxy } = getCurrentInstance();
        //初始化应用表单对象
        const queryForm = reactive({});
        //初始化应用列表数据
        const appList = ref([]);
        //初始化分页对象
        const pager = reactive({
            pageNum: 1,
            pageSize: 10
        });
        //选中应用列表的对象
        const checkedAppIds = ref([]);
        //弹框显示对象
        const showModal = ref(false);
        //控制进度显示对象
        const showProgress = ref(false);
        //上传进度
        const upLoadProgress = ref('');
        //应用地址地址
        const appUrl = ref('');
        //新增应用表单对象
        const appForm = reactive({});
        //定义应用操作行为
        const action = ref('add');
        //定义动态表格格式
        const columns = reactive([
            {
                label: "应用ID",
                prop: "appId",
                width: 180,
            },
            {
                label: "应用名称",
                prop: "appName",
                width: 150,
            },
            {
                label: "应用类型",
                prop: "appType",
                formatter(row, column, value) {
                    return {
                        '0': '安卓端',
                        '1': '苹果端'
                    }[value]
                }
            },
            {
                label: "应用版本",
                prop: "version"
            },
            {
                label: "创建时间",
                prop: "createTime",
                formatter(row, column, value) {
                    return utils.formateDate(new Date(value));
                }
            }
        ]);
        //初始化接口调用
        onMounted(() => {
            getAppList();
        })
        // 获取应用列表
        const getAppList = async () => {
            let params = { ...queryForm, ...pager };
            try {
                const { list, total } = await proxy.$api.getAppList(params);
                appList.value = list;
                pager.totalCount = total;
            } catch (error) {
                console.log(proxy.$api);
            }
        };
        //查询事件，获取应用列表
        const handleQuery = () => {
            getAppList();
        }
        // 重置查询表单
        const handleReset = (form) => {
            proxy.$refs[form].resetFields();
            getAppList();
        };
        // 分页事件处理
        const handleCurrentChange = (current) => {
            pager.pageNum = current;
            getAppList();
        };
        //表格多选
        const handleSelectionChange = (list) => {
            let arr = [];
            list.map(item => {
                arr.push(item.appId);
            })
            checkedAppIds.value = arr;
        }
        //批量删除
        const handlePatchDelete = async () => {
            if (checkedAppIds.value.length == 0) {
                proxy.$message.error('请选择要删除的应用');
                return;
            }
            const res = await proxy.$api.appDelete({
                appIds: checkedAppIds.value
            })
            if (res.rows > 0) {
                proxy.$message.success('删除成功');
                getAppList();
            } else {
                proxy.$message.error('删除失败');
            }

        };
        //应用日志单个删除
        const handleDelete = async (row) => {
            await proxy.$api.appDelete({
                appIds: [row.appId]
            })
            proxy.$message.success('删除成功');
            getAppList();
        };
        //应用新增
        const handleCreate = () => {
            action.value = 'add';
            showModal.value = true;
        }
        // 应用弹窗关闭
        const handleClose = () => {
            showModal.value = false;
            appUrl.value = '';
            handleReset("dialogForm");
        };
        // 应用提交
        const handleSubmit = () => {
            proxy.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    appForm.fileUrl = appUrl.value;
                    let params = toRaw(appForm);
                    params.action = action.value;
                    if (action.value == 'add') {
                        let res = await proxy.$api.appSubmit(params);
                        proxy.$message.success("应用创建成功");
                    } else {
                        let res = await proxy.$api.appUpdate(params);
                        proxy.$message.success("应用修改成功");
                    }
                    showModal.value = false;
                    appUrl.value = '';
                    handleReset("dialogForm");
                    getAppList();
                }
            });
        };
        // 应用编辑
        const handleEdit = (row) => {
            action.value = "edit";
            showModal.value = true;
            proxy.$nextTick(async () => {
                try {
                    const { app } = await proxy.$api.getAppById({ appId: row.appId });
                    appUrl.value = app.fileUrl;
                    Object.assign(appForm, app);
                } catch (error) {
                    console.log(proxy.$api);
                }
            });
        };
        //上传文件直传
        const uploadFile = async (file) => {
            const { uploadUrl, fileUrl } = await proxy.$api.getUploadUrl({ fileName: file.file.name, fileSize: file.file.size, fileType: "3" });
            await axios.request({
                url: uploadUrl,
                method: 'PUT',
                data: file.file,
                headers: { 'Content-Type': 'application/octet-stream' },
                onUploadProgress: function (progressEvent) {
                    // 对原生进度事件的处理
                    if (progressEvent.lengthComputable) {
                        upLoadProgress.value = Math.round(progressEvent.loaded / progressEvent.total * 100) + ""//实时获取上传进度
                        if (upLoadProgress.value === '100') {
                            showProgress.value = false;
                            appUrl.value = fileUrl;
                        } else {
                            showProgress.value = true;
                        }
                    }
                }
            })
        };
        // 上传进度
        const handleProgressClose = () => {
            showProgress.value = false;
        }
        return {
            queryForm,
            appList,
            columns,
            pager,
            checkedAppIds,
            showModal,
            showProgress,
            upLoadProgress,
            appUrl,
            appForm,
            action,
            getAppList,
            handleQuery,
            handleReset,
            handleCurrentChange,
            handleSelectionChange,
            handlePatchDelete,
            handleDelete,
            handleCreate,
            handleClose,
            handleSubmit,
            handleEdit,
            uploadFile,
            handleProgressClose
        }
    }
}
</script>

<style lang="scss"></style>